<template>
  <!-- 展示 -->
  <div
    style="
      background-color: #fff;
      padding: 12px;
      text-align: left;
      margin-top: 18px;
    "
  >
    <el-row>
      <el-col :span="4">
        <div style="line-height: 32px" ref="titleColRef">轮播图列表</div>
      </el-col>
      <el-col :span="20" style="text-align: right">
        <el-button
          v-if="resources.indexOf('Products-Slideshow-Add') > -1"
          type="primary"
          @click="showDrawer('add', '新增轮播图')"
        >
          新增轮播图
        </el-button>
      </el-col>
    </el-row>
    <el-table
      :height="tabelHeight"
      :data="listResponse"
      border
      :max-height="tabelHeight"
      style="width: 100%; margin-top: 18px"
      empty-text="暂无数据"
      table-layout="auto"
      v-loading="loading"
    >
      <el-table-column prop="sort" label="排序" />
      <el-table-column label="状态" prop="status">
        <template
          #default="scope"
          v-if="resources.indexOf('Products-Slideshow-Modify') > -1"
        >
          <div style="display: flex; align-items: center">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              :loading="switchLoading"
              :width="65"
              inline-prompt
              active-text="已启用"
              inactive-text="已禁用"
              @change="handelChangestatus(scope.row)"
            />
          </div>
        </template>
        <template #default="scope" v-else>
          <div style="display: flex; align-items: center">
            <el-tag type="success" effect="dark" v-if="scope.row.status === 1"
              >已启用</el-tag
            >
            <el-tag type="danger" effect="dark" v-else>禁止</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="轮播图">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.fileImageVo.thumbnailPath"
              :preview-src-list="[scope.row.fileImageVo.previewPath]"
              fit="cover"
              :hide-on-click-modal="true"
              :lazy="true"
              preview-teleported
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="90"
        v-if="
          resources.indexOf('Products-Slideshow-Modify') > -1 ||
          resources.indexOf('Products-Slideshow-Remove') > -1
        "
      >
        <template #default="scope">
          <el-breadcrumb separator="|">
            <el-tooltip
              v-if="resources.indexOf('Products-Slideshow-Modify') > -1"
              class="box-item"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-breadcrumb-item>
                <el-icon
                  class="icon-btn"
                  :size="18"
                  style="margin-top: 2px"
                  color="#409EFF"
                  @click="showDrawer('edit', '编辑轮播图信息', scope.row)"
                >
                  <Edit />
                </el-icon>
              </el-breadcrumb-item>
            </el-tooltip>
            <el-tooltip
              v-if="resources.indexOf('Products-Slideshow-Remove') > -1"
              class="box-item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-breadcrumb-item>
                <el-popconfirm
                  title="确定删除该轮播图信息？"
                  @confirm="handelRemove(scope.row.id)"
                >
                  <template #reference>
                    <el-icon
                      class="icon-btn"
                      :size="18"
                      style="margin-top: 2px"
                      color="#F56C6C"
                    >
                      <Delete />
                    </el-icon>
                  </template>
                </el-popconfirm>
              </el-breadcrumb-item>
            </el-tooltip>
          </el-breadcrumb>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-drawer
    v-model="drawer.show"
    direction="rtl"
    @close="closeDrawer"
    append-to-body
    size="30%"
  >
    <template #header>
      <h4>{{ drawer.title }}</h4>
    </template>
    <template #default>
      <el-form
        :model="slideshowModify"
        :rules="rules"
        ref="ruleFormRef"
        label-width="120px"
        v-loading="cascaderLoading"
      >
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="slideshowModify.sort"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="slideshowModify.status"
            :active-value="1"
            :inactive-value="0"
            :width="65"
            inline-prompt
            active-text="已启用"
            inactive-text="已禁用"
          />
        </el-form-item>

        <el-form-item label="轮播图" prop="imgCover">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handelChangeImg"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div style="color: red">最多上传一张</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="closeDrawer">取消</el-button>
        <el-button
          type="primary"
          @click="handelAdd"
          v-if="drawer.type === 'add'"
          >提交</el-button
        >
        <el-button type="primary" @click="handelModify" v-else>修改</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import store from "../store";
import { ref, reactive, onMounted, nextTick } from "vue";
import {
  doSave,
  doList,
  doModify,
  doModifyStatus,
  doRemove,
} from "../api/slideshow";
import { ElMessage, FormRules, ElLoading } from "element-plus";
import { Edit, Delete, Plus } from "@element-plus/icons-vue";
import { log } from "mathjs";
const resources = store.state.userStore.resources;
const drawer = ref({
  show: false,
  title: "新增轮播图",
  type: "add",
});
const closeDrawer = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  drawer.value.show = false;
  slideshowModify.value = JSON.parse(JSON.stringify(copy));
  imageUrl.value = "";
  file.value = {};
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
};
const slideshowModify = ref({
  sort: 0,
  status: 1,
  imgCover: "",
});
const copy = {
  sort: 0,
  status: 1,
  imgCover: "",
};

const isImgCover = (rule: any, value: any, callback: any) => {
  if (
    imageUrl.value === "" ||
    imageUrl.value === undefined ||
    imageUrl.value === null
  ) {
    return callback(new Error("请选择轮播图"));
  } else {
    callback();
  }
};
const rules = ref<FormRules>({
  status: [
    {
      required: true,
      message: "请输入状态",
      trigger: "blur",
    },
  ],
  sort: [
    {
      required: true,
      message: "请输入排序",
      trigger: "blur",
    },
  ],
  imgCover: [
    {
      validator: isImgCover,
      required: true,
      trigger: "blur",
    },
  ],
});

//级联选项
const cascaderOption = ref([]);

//显示增加修改抽屉
const showDrawer = (type: string, title: string, data?: any) => {
  drawer.value.type = type;
  drawer.value.show = true;
  drawer.value.title = title;

  if (type === "edit") {
    slideshowModify.value = JSON.parse(JSON.stringify(data));
    imageUrl.value = data.fileImageVo.previewPath;
  }
};
const cascaderLoading = ref(false);
const ruleFormRef = ref();
const handelAdd = () => {
  if (file.value.raw === undefined || file.value.raw === null) {
    return ElMessage({
      message: "请上传图片",
      grouping: true,
      type: "error",
    });
  }
  const loading = ElLoading.service({
    lock: true,
    text: "新增中，请稍后...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  if (!ruleFormRef) return loading.close();
  ruleFormRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      const slideshowValue = JSON.parse(JSON.stringify(slideshowModify.value));
      const formData = new FormData();
      formData.append("files", file.value.raw!);
      formData.append("slideshow", JSON.stringify(slideshowValue));
      doSave(formData)
        .then((res: any) => {
          if (res.code != 200) {
            ElMessage({
              message: res.msg === null ? "系统后台异常！" : res.msg,
              grouping: true,
              type: "error",
            });
          } else {
            ElMessage({
              message: res.msg,
              grouping: true,
              type: "success",
            });
            closeDrawer();
            handelList();
          }
          loading.close();
        })
        .catch((err: any) => {
          loading.close();
          ElMessage({
            message: err,
            grouping: true,
            type: "error",
          });
        });
    } else {
      loading.close();
    }
  });
};

const loading = ref(false);
const listResponse = ref([]);
const tabelHeight = ref(
  (window.innerHeight ||
    document.documentElement.clientHeight ||
    document.body.clientHeight) - 365
);
const handelList = () => {
  loading.value = true;
  setTimeout(() => {
    doList()
      .then((res: any) => {
        if (res.code != 200) {
          ElMessage({
            message: res.msg === null ? "系统后台异常！" : res.msg,
            grouping: true,
            type: "error",
          });
        } else {
          listResponse.value = res.data;
        }
        loading.value = false;
      })
      .catch((err: any) => {
        ElMessage({
          message: err,
          grouping: true,
          type: "error",
        });
        loading.value = false;
      });
  }, 300);
};
const handelModify = () => {
  const loading = ElLoading.service({
    lock: true,
    text: "修改中，请稍后...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  if (!ruleFormRef) return loading.close();
  ruleFormRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      const formDate = new FormData();
      formDate.append("files", file.value.raw!);
      formDate.append("slideshow", JSON.stringify(slideshowModify.value));
      doModify(formDate)
        .then((res: any) => {
          if (res.code != 200) {
            ElMessage({
              message: res.msg === null ? "系统后台异常！" : res.msg,
              grouping: true,
              type: "error",
            });
          } else {
            ElMessage({
              message: res.msg,
              grouping: true,
              type: "success",
            });
            closeDrawer();
            handelList();
          }
          loading.close();
        })
        .catch((err: any) => {
          ElMessage({
            message: err,
            grouping: true,
            type: "error",
          });
          loading.close();
        });
    }
  });
};
const file = ref({});
const imageUrl = ref("");
const handelChangeImg = (uploadFile: any, uploadFiles: any) => {
  file.value = uploadFile;

  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};
const switchLoading = ref(false);
const handelChangestatus = (data: any) => {
  doModifyStatus(data.id, data.status)
    .then((res: any) => {
      if (res.code != 200) {
        ElMessage({
          message: res.msg === null ? "系统后台异常！" : res.msg,
          grouping: true,
          type: "error",
        });
      } else {
        ElMessage({
          message: res.msg,
          grouping: true,
          type: "success",
        });
        handelList();
      }
    })
    .catch((err: any) => {
      ElMessage({
        message: err,
        grouping: true,
        type: "error",
      });
    });
};

const handelRemove = (id: string) => {
  const ids = [id];
  doRemove({ ids })
    .then((res: any) => {
      if (res.code != 200) {
        ElMessage({
          message: res.msg === null ? "系统后台异常！" : res.msg,
          grouping: true,
          type: "error",
        });
      } else {
        ElMessage({
          message: res.msg,
          grouping: true,
          type: "success",
        });
        handelList();
      }
    })
    .catch((err: any) => {
      ElMessage({
        message: err,
        grouping: true,
        type: "error",
      });
    });
};
const productInfo = ref({
  title: "",
  productType: "",
  price: "",
  brand: "",
  areaMin: "",
  areaMax: "",
  discount: "",
});

onMounted(() => {
  handelList();
});
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style scope>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-icon:hover {
  cursor: pointer;
}
</style>